package org.example.erat.model;

import java.io.File;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReportAnalyzer {
    private static final Pattern REPORT_FILE_PATTERN =
            Pattern.compile("(\\d+)_([^_]+)_实验(\\d+)\\.(pdf|doc|docx|txt)");

    private final StudentManager studentManager;
    private Map<Integer, List<String>> missingStudentsByExperiment; // 实验编号 -> 缺交学生列表
    private Map<String, List<String>> missingReportsByStudent; // 学号 -> 缺交实验列表
    private List<String> allFileNames; // 存储所有文件名
    private int totalExperiments;

    public ReportAnalyzer(StudentManager studentManager) {
        this.studentManager = studentManager;
        this.missingStudentsByExperiment = new ConcurrentHashMap<>();
        this.missingReportsByStudent = new ConcurrentHashMap<>();
        this.allFileNames = Collections.synchronizedList(new ArrayList<>());
    }
    public Map<String, List<String>> getStudentStatistics() {
        Map<String, List<String>> statistics = new HashMap<>();
        for (Student student : studentManager.getAllStudents()) {
            String studentId = student.getStudentId();
            List<String> missingExperiments = missingReportsByStudent.getOrDefault(studentId, Collections.emptyList());

            if (!missingExperiments.isEmpty()) {
                // 构建包含缺交次数和缺交实验列表的统计数据
                List<String> stats = Arrays.asList(
                        String.valueOf(missingExperiments.size()), // 缺交次数
                        String.join(", ", missingExperiments)     // 缺交实验列表
                );
                statistics.put(studentId, stats);
            }
        }
        return statistics;
    }

    // 添加getExperimentStatistics()方法
    public Map<String, List<String>> getExperimentStatistics() {
        Map<String, List<String>> statistics = new LinkedHashMap<>(); // 使用LinkedHashMap保持顺序

        // 遍历所有实验，收集缺交信息
        for (Map.Entry<Integer, List<String>> entry : missingStudentsByExperiment.entrySet()) {
            int experimentNumber = entry.getKey();
            List<String> missingStudents = entry.getValue();

            // 构建缺交学生姓名列表
            List<String> missingStudentNames = new ArrayList<>();
            for (String studentId : missingStudents) {
                Student student = studentManager.getStudent(studentId);
                if (student != null) {
                    missingStudentNames.add(student.getName() + "(" + studentId + ")");
                }
            }

            // 构建统计数据：[缺交人数, 缺交学生列表]
            List<String> stats = Arrays.asList(
                    String.valueOf(missingStudents.size()),
                    String.join(", ", missingStudentNames)
            );

            statistics.put("实验" + experimentNumber, stats);
        }

        return statistics;
    }

    // 添加获取提交率的方法
    public Map<Integer, Double> getSubmissionRates() {
        Map<Integer, Double> rates = new TreeMap<>();
        int totalStudents = studentManager.getAllStudents().size();

        for (Map.Entry<Integer, List<String>> entry : missingStudentsByExperiment.entrySet()) {
            int experimentNumber = entry.getKey();
            int missingCount = entry.getValue().size();
            double submissionRate = ((double) (totalStudents - missingCount) / totalStudents) * 100;

            rates.put(experimentNumber, submissionRate);
        }

        return rates;
    }
    public void analyzeReports(String reportsDirectoryPath) {
        // 重置数据
        missingStudentsByExperiment.clear();
        missingReportsByStudent.clear();
        allFileNames.clear();

        // 打印分析开始信息
        System.out.println("\n=== 开始分析实验报告 ===");
        System.out.println("扫描目录: " + reportsDirectoryPath);

        File directory = new File(reportsDirectoryPath);
        if (!directory.exists() || !directory.isDirectory()) {
            System.err.println("错误: 目录不存在或不是有效目录");
            return;
        }

        // 获取所有文件并打印
        File[] files = directory.listFiles();
        if (files == null || files.length == 0) {
            System.out.println("警告: 目录为空");
            return;
        }

        System.out.println("\n=== 文件夹中的全部文件名 ===");
        for (File file : files) {
            String fileName = file.getName();
            allFileNames.add(fileName);
            System.out.println(fileName);
        }

        // 处理所有报告文件
        System.out.println("\n=== 文件名匹配分析 ===");
        for (File file : files) {
            processReportFile(file);
        }

        // 计算缺交情况
        calculateMissingReports();

        // 打印分析结果摘要
        printAnalysisSummary();
    }

    private void processReportFile(File file) {
        String fileName = file.getName();
        Matcher matcher = REPORT_FILE_PATTERN.matcher(fileName);

        if (matcher.matches()) {
            String studentId = matcher.group(1);
            String studentName = matcher.group(2);
            int experimentNumber = Integer.parseInt(matcher.group(3));

            // 检查学生是否存在
            if (!studentManager.containsStudent(studentId)) {
                System.out.println("警告: 文件 " + fileName + " 中的学号 " + studentId + " 不存在于学生信息中");
                return;
            }

            // 记录实验编号和已提交学生
            if (!missingStudentsByExperiment.containsKey(experimentNumber)) {
                // 初始化实验编号对应的已提交学生列表
                missingStudentsByExperiment.put(experimentNumber, new ArrayList<>());
            }

            // 将学生标记为已提交此实验
            List<String> submittedStudents = missingStudentsByExperiment.get(experimentNumber);
            if (!submittedStudents.contains(studentId)) {
                submittedStudents.add(studentId);
            }

            System.out.println("匹配成功: " + fileName + " -> 学号: " + studentId + ", 实验: " + experimentNumber);
        } else {
            System.out.println("匹配失败: " + fileName);
        }
    }

    private void calculateMissingReports() {
        // 获取所有学生ID
        List<Student> allStudents = studentManager.getAllStudents();

        // 如果没有找到任何实验报告
        if (missingStudentsByExperiment.isEmpty()) {
            System.out.println("警告: 没有找到符合格式的实验报告文件");
            return;
        }

        // 确定总实验数（最大实验编号）
        totalExperiments = Collections.max(missingStudentsByExperiment.keySet());
        System.out.println("\n=== 分析结果 ===");
        System.out.println("总实验数: " + totalExperiments);

        // 初始化每个学生的缺交实验列表
        for (Student student : allStudents) {
            missingReportsByStudent.put(student.getStudentId(), new ArrayList<>());
        }

        // 检查每个实验的缺交学生
        for (int expNum = 1; expNum <= totalExperiments; expNum++) {
            List<String> submittedStudents = missingStudentsByExperiment.getOrDefault(expNum, new ArrayList<>());
            List<String> missingStudents = new ArrayList<>();

            // 找出缺交的学生
            for (Student student : allStudents) {
                if (!submittedStudents.contains(student.getStudentId())) {
                    missingStudents.add(student.getStudentId());
                    // 记录该学生缺交的实验
                    missingReportsByStudent.get(student.getStudentId()).add("实验" + expNum);
                }
            }

            missingStudentsByExperiment.put(expNum, missingStudents);

            // 打印每个实验的提交情况
            System.out.println("实验" + expNum + ": 提交 " + (allStudents.size() - missingStudents.size()) +
                    " 人, 缺交 " + missingStudents.size() + " 人");
        }

        // 打印缺交统计
        System.out.println("\n=== 缺交统计 ===");
        int missingCount = 0;
        for (Map.Entry<String, List<String>> entry : missingReportsByStudent.entrySet()) {
            if (!entry.getValue().isEmpty()) {
                missingCount++;
                String studentId = entry.getKey();
                String studentName = studentManager.getStudent(studentId).getName();
                System.out.println(studentId + " (" + studentName + "): " +
                        String.join(", ", entry.getValue()));
            }
        }

        System.out.println("总共有 " + missingCount + " 名学生有缺交记录");
    }

    private void printAnalysisSummary() {
        // 打印分析摘要
        System.out.println("\n=== 分析摘要 ===");
        System.out.println("学生总数: " + studentManager.getAllStudents().size());
        System.out.println("找到实验报告文件数: " +
                allFileNames.stream().filter(name -> REPORT_FILE_PATTERN.matcher(name).matches()).count());
        System.out.println("识别出的实验数: " + missingStudentsByExperiment.size());
    }

    // 其他方法保持不变...
}